package com.homelock.dubbo.service;

import com.pi.base.util.cache.RedisUtil;
import redis.clients.jedis.Jedis;

import java.io.UnsupportedEncodingException;
import java.util.Collections;

public class RedisLockUtil {
    public static final String OK = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "EX";
    private static final Long RELEASE_SUCCESS = 1L;

    public static final String UNLOCK_LUA = "if redis.call(\"get\",KEYS[1]) == ARGV[1] "
            + "then    return redis.call(\"del\",KEYS[1]) " + "else " + "    return 0 " + "end ";

    public static Long getLong(String lockKey) {
        try{
            return Long.valueOf(RedisUtil.get(lockKey));
        }catch (UnsupportedEncodingException e){
            return 0L;
        }
    }
    /**
     * 获取锁
     * @param lockKey
     * @param lockValue
     * @param expireSeconds
     * @return
     */
    public static boolean trylock(String lockKey,String lockValue,Integer expireSeconds){
        String result = "";
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getInstance();
            result = jedis.set(lockKey,lockValue,SET_IF_NOT_EXIST,SET_WITH_EXPIRE_TIME,expireSeconds);
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return OK.equalsIgnoreCase(result);
    }


    /**
     * 释放分布式锁 (非自己释放，超时之后其他请求释放该锁)
     * @param lockKey 锁
     * @return 是否释放成功
     */
    public static boolean releaseDistributedLockByOthers(String lockKey) {
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getInstance();
            Object result = jedis.del(lockKey);
            if (RELEASE_SUCCESS.equals(result)) {
                return true;
            }
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 释放分布式锁
     * @param lockKey 锁
     * @param lockValue 请求标识
     * @return 是否释放成功
     */
    public static boolean releaseDistributedLock(String lockKey, String lockValue) {
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getInstance();
          Object result = jedis.eval(UNLOCK_LUA, Collections.singletonList(lockKey), Collections.singletonList(lockValue));
          if (RELEASE_SUCCESS.equals(result)) {
                return true;
            }
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return false;
    }

}
